<template>
  <div class="login_container">
    <div class="login_box">
      <!-- 图标区 -->
      <div class="login_log" v-if="loginType === 'account'"></div>
      <!-- 登录表单区 -->
      <div class="form-box" v-if="loginType === 'account'">
        <el-form ref="loginFormRef" :model="loginForm" :rules="ruleInline">
          <el-form-item prop="loginAccount">
            <el-input
              prefix-icon="User"
              v-model="loginForm.loginAccount"
              placeholder="请输入账号..."
            >
              <template #suffix>
                <el-icon
                  v-if="loginForm.loginAccount"
                  @click="deleteLoginAccount"
                  style="cursor: pointer"
                >
                  <Delete />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="passWord">
            <el-input
              prefix-icon="Lock"
              v-model="loginForm.passWord"
              placeholder="请输入密码..."
              show-password
              style="margin-top: 5px"
            >
              <template #suffix>
                <el-icon
                  v-if="loginForm.passWord"
                  @click="deletePassword"
                  style="cursor: pointer"
                >
                  <Delete />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <div class="auto-login">
            <el-checkbox v-model="autoLogin" size="large">自动登录</el-checkbox>
            <a>忘记密码</a>
          </div>
          <el-form-item>
            <el-button
              type="primary"
              @click="login()"
              :loading="loginLoading"
              style="width: 100%"
              >登录</el-button
            >
          </el-form-item>
          <div class="create-user">
            <span>还没有账号？</span>
            <a>新建账号</a>
          </div>
        </el-form>
      </div>
      <!-- 第三方登录 -->
      <div class="form-third" v-else>
        <!-- 提示信息-->
        <div class="tips">扫码登录</div>
        <div class="tips-b">请使用zz-admin移动端扫码登录</div>
        <div class="qrcode"></div>
        <div class="other-login">
          <div class="other-login-title">其他登录方式</div>
          <div class="other-login-icons">
            <el-row justify="space-between">
              <div v-for="fit in fitList" :key="fit">
                <el-col>
                  <el-avatar
                    :src="fit.url"
                    :size="40"
                    @click="handleThirdPartyLogin(fit.title)"
                  ></el-avatar>
                </el-col>
              </div>
            </el-row>
          </div>
        </div>
      </div>
      <!-- 切换登录方式 -->
      <div class="login-other" @click="changeLoginType"></div>
    </div>
  </div>
</template>

<script setup>

import { ref, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import qq from "@/assets/png/qq.png";
import wechat from "@/assets/png/wechat.png";
import weibo from "@/assets/png/weibo.png";
import gitee from "@/assets/png/gitee.png";
import { loadRemoteData } from "@/i18n";

const { proxy } = getCurrentInstance();

const loginForm = ref({ loginAccount: "", passWord: "" });
const ruleInline = ref({
  loginAccount: [{ required: true, message: "请输入账号", trigger: "blur" }],
  passWord: [{ required: true, message: "请输入密码", trigger: "blur" }],
});
const autoLogin = ref(false);
const loginLoading = ref(false);

const deleteLoginAccount = () => {
  loginForm.value.loginAccount = "";
};
const deletePassword = () => {
  loginForm.value.passWord = "";
};

const loginType = ref("account");
const changeLoginType = () => {
  loginType.value = loginType.value === "account" ? "thirdParty" : "account";
};

const loginFormRef = ref(null);
const login = async () => {
  loginFormRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    loginLoading.value = true;
    let loginData = {
      loginAccount: loginForm.value.loginAccount,
      passWord: loginForm.value.passWord,
    };
    try {
      const loginRes = await proxy.$API.auth.auth.login.post(loginData);
      if (loginRes.code == "01") {
        // 在登录成功之后：从登录接口获取token、当前登陆人信息
        await loginSuccess(loginRes.data);
        // 再调用接口获取菜单、字典、组织
        await getBasedata(loginRes.data.userDto);
        // 跳转到首页
        proxy.$router.push("/home");
        loginLoading.value = false;
      } else {
        // this.$Message.error(loginRes.message)
        loginLoading.value = false;
      }
    } catch (error) {}
  });
};

const loginSuccess = async (data) => {
  // 存储token
  proxy.$TOOL.session.set("token", data.token);
  // 存储当前用户信息
  proxy.$TOOL.session.set("userInfo", data.userDto);
  // 将activeMenu设置为1
  proxy.$TOOL.data.set("activeMenu", 1);
  // 同步缓存
  const savedLanguage = localStorage.getItem("language") || "zh-CN";
  await loadRemoteData(savedLanguage);
  // 打印信息
  ElMessage.success("登录成功");
};

// 获取基础数据：菜单、字典、组织
const getBasedata = async (userDto) => {
  let res = await proxy.$API.auth.auth.getBasedata.get(userDto.userId);
  if (res.code == "01") {
    let data = res.data;
    // 存储菜单
    proxy.$TOOL.session.set("menus", data.menuDtos);
    // TODO: 存储字典
    // TODO: 存储组织
  }
};

const fitList = ref([
  { url: wechat, title: "微信" },
  { url: qq, title: "QQ" },
  { url: weibo, title: "微博" },
  { url: gitee, title: "Gitee" },
]);

const loginWithGitee = () => {
  window.location.href = "http://localhost:9094/oauth2/authorization/gitee";
};
const loginWithQQ = () => {
  console.log("QQ登录");
};
const loginWithWechat = () => {
  console.log("微信登录");
};
const handleThirdPartyLogin = (title) => {
  switch (title) {
    case "微信":
      loginWithWechat();
      break;
    case "QQ":
      loginWithQQ();
      break;
    case "微博":
      loginWithWeibo();
      break;
    case "Gitee":
      loginWithGitee();
      break;
    default:
      break;
  }
};

const loginWithWeibo = () => {
  console.log("微博登录");
};


const editCodeGenRef = ref(null);
const editCodeGenIsOpen = ref(false);
</script>

<style lang="less" scoped>
/* 登录页总样式 */
.login_container {
  height: 100vh;
  background-image: url("@/assets/png/login_new.png");
  background-size: cover; /* 或者使用 contain 或 100% 100% */
  background-repeat: no-repeat;
  background-position: center;

  /** 登录框 */
  .login_box {
    width: 350px;
    height: 450px;
    background: rgba(246, 249, 255, 0.8);
    border-radius: 10px;
    position: absolute;
    right: 75%;
    top: 50%;
    transform: translate(50%, -50%);
    backdrop-filter: blur(20px);
    box-shadow: 10px 30px 30px rgba(0, 0, 0, 0.1);

    .login_log {
      position: relative;
      text-align: center;
      margin-top: 80px;
      margin-left: 40px;
      height: 18px;
      background-image: url("@/assets/png/logo_title.png");
      background-size: contain; /* 或者使用 contain 或 100% 100% */
      background-repeat: no-repeat;
      background-position: center;
    }
    .login_log::before {
      content: "";
      position: absolute;
      left: 0%;
      top: 40%;
      transform: translateY(-50%);
      width: 100px; /* 图标自定义宽度 */
      height: 40px; /* 图标自定义高度 */
      background-image: url("@/assets/png/logo_new.png"); /* 图标的路径 */
      /* 其他图标样式属性 */
      background-size: contain; /* 或者使用 contain 或 100% 100% */
      background-repeat: no-repeat;
      background-position: center;
    }
    .form-box {
      position: absolute;
      bottom: 100px;
      width: 100%;
      height: 200px;
      padding: 0 70px;
      box-sizing: border-box;
    }

    .form-third {
      .tips {
        display: flex;
        justify-content: center;
        margin-top: 50px;
        font-size: 20px;
        color: black;
        font-weight: 800;
      }

      .tips-b {
        display: flex;
        justify-content: center;
        margin-top: 10px;
        font-size: 14px;
        color: #606266;
        font-weight: 500;
      }

      .qrcode {
        width: 200px;
        height: 200px;
        margin: 0 auto;
        margin-top: 10px;
        background-image: url("@/assets/png/qrcode.png");
        background-size: cover; /* 使图片覆盖整个区域 */
      }

      .other-login-title {
        display: flex;
        justify-content: center;
        margin-top: 40px;
        font-size: 12px;
        color: #606266;
        font-weight: 500;
      }

      .other-login-icons {
        margin-top: 10px;
        margin-left: 50px;
        margin-right: 50px;
      }
    }

    .login-other {
      position: absolute;
      top: 0;
      right: 0;
      width: 0;
      height: 0;
      border-top: 50px solid rgb(235, 237, 240, 0.8); /* 三角形的颜色 */
      border-left: 50px solid transparent;
      cursor: pointer;
      border-radius: 0 10px 0 0;
    }

    .login-other::before {
      content: "";
      position: absolute;
      top: -40px; /* 调整位置 */
      right: 10px;
      width: 30px; /* 图片宽度 */
      height: 30px; /* 图片高度 */
      background-image: url("@/assets/png/qrcode_b.png"); /* 图片路径 */
      background-size: cover; /* 使图片覆盖整个区域 */
      border-radius: 0 10px 0 0; /* 保持与父元素一致的圆角 */
      clip-path: polygon(0 0, 100% 0, 100% 100%); /* 裁剪图片为三角形 */
    }
  }

  .auto-login {
    margin-bottom: 18px;
  }

  .auto-login a {
    float: right;
    line-height: 40px;
    font-size: 14px;
  }

  .create-user {
    margin-bottom: 18px;
    text-align: center;
    color: #606266;
    font-size: 14px;
  }
}

:deep(.el-avatar) {
  --el-avatar-bg-color: rgba(246, 249, 255, 0);
  cursor: pointer;
  transition: background-color 0.3s;
}

:deep(.el-avatar:hover) {
  --el-avatar-bg-color: rgba(200, 200, 200, 0.5);
}
</style>
